<template>
  <div class="news-detail-container">
    <!-- 页面标题区域 -->
    <el-page-header @back="goBack" :content="news.title" class="page-header">
    </el-page-header>

    <!-- 资讯详情卡片 -->
    <el-card class="news-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="news-title">{{ news.title }}</span>
        <el-tag type="info" class="news-date">{{ news.type }}</el-tag>
      </div>

      <div class="news-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-image
                :src="news.avatar"
                :preview-src-list="[news.avatar]"
                class="news-avatar"
                fit="cover">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </el-col>

          <el-col :span="16">
            <el-descriptions class="news-meta" :column="2" border>
              <el-descriptions-item label="撰稿人">
                <el-tag size="small">{{ news.author }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="来源">
                <el-tag size="small">{{ news.source }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="标签">
                <el-tag size="small">{{ news.tag }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="发布时间">
                <el-tag size="small">{{ news.current }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="点赞数量">
                <el-tag size="small">{{ thumbsCount }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="评论数量">
                <el-tag size="small">{{ reviewsCount }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <div class="news-footer">
              <el-button type="primary" icon="el-icon-check" @click="handleReview">评论</el-button>
              <el-button type="success" icon="el-icon-thumb" @click="handleThumbs">点赞</el-button>
              <el-button type="info" icon="el-icon-share" @click="handleShare">分享</el-button>
            </div>
          </el-col>
        </el-row>

        <v-md-editor v-model="news.content" mode="preview" height="auto"></v-md-editor>

      </div>
    </el-card>

    <div class="comment-container">
      <!-- 评论列表 -->
      <el-row :gutter="20" class="comment-list">
        <el-col :span="12" v-for="comment in reviews" :key="comment.id">
          <el-card class="comment-card" shadow="hover">
            <div class="comment-header">
              <el-avatar :src="comment.user.avatar" class="comment-avatar"></el-avatar>
              <div class="comment-user-info">
                <p class="comment-username">{{ comment.user.name }}</p>
                <p class="comment-date">{{ formatDate(comment.current) }}</p>
              </div>
            </div>
            <div class="comment-content">
              <p>{{ comment.content }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>
import api from "@/api";
import {getCache} from "@/utils/useCache";
import {formatDate} from "../../utils/date";

export default {
  name: "ActiveDetail",
  data() {
    return {
      news: {
        title: "加载中...",
        content: "",
        type: "",
        author: "",
        source: "",
        current: "",
        avatar: "",
      },
      thumbsCount: 0,
      reviewsCount: 0,
      reviews: 0,
    };
  },
  mounted() {
    this.fetchNewsDetail();
  },
  methods: {
    formatDate,
    // 获取资讯详情
    async fetchNewsDetail() {
      const id = this.$route.query.id;
      try {
        const response = await api.news.newsId(id);
        this.news = response.data.data;

        const res = await api.thumbs.thumbsList();
        this.thumbsCount = res.data.data.filter((item) =>
            item.newsId == id
        ).length;

        const r = await api.review.reviewList();
        this.reviews = r.data.data.filter((item) =>
            item.newsId == id
        );
        this.reviewsCount = this.reviews.length;

        let temp = [];
        for (let i = 0; i < this.reviews.length; i++) {
          let review = this.reviews[i];
          let user = await api.user.userId(review.userId);
          const item = {
            user: user.data.data,
            ...review,
          }
          temp.push(item);
        }
        this.reviews = temp;

      } catch (error) {
        this.$message.error('获取资讯详情失败');
        console.error(error);
      }
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    // 评论
    handleReview() {
      this.$prompt('请输入评论内容', '评论', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '评论内容不能为空'
      }).then(({value}) => {
        const params = {
          newsId: this.news.id,
          userId: getCache('USERINFO').id,
          content: value,
        }
        api.review.reviewAppend(params).then(response => {
          if (response.data.code === 200) {
            this.$message.success('评论成功');
            this.news.reviewsCount += 1;
            this.fetchNewsDetail();
          } else {
            this.$message.error('评论失败');
          }
        }).catch(error => {
          console.error(error);
        });
      }).catch(() => {
        this.$message.info('取消评论');
      });
    },
    // 点赞
    async handleThumbs() {
      let res = await api.thumbs.thumbsList();
      for (let i = 0; i < res.data.data.length; i++) {
        let datum = res.data.data[i];
        if (datum.userId == getCache('USERINFO').id && datum.newsId == this.news.id) {
          this.$message.success('您已经点过赞了');
          return;
        }
      }
      const params = {
        newsId: this.news.id,
        userId: getCache('USERINFO').id,
      }
      api.thumbs.thumbsAppend(params).then(response => {
        if (response.data.code === 200) {
          this.$message.success('点赞成功');
          this.news.thumbsCount += 1;
        } else {
          this.$message.error('点赞失败');
        }
      }).catch(error => {
        console.error(error);
      });
    },
    // 分享资讯
    handleShare() {
      const currentUrl = window.location.href; // 获取当前页面的URL
      navigator.clipboard.writeText(currentUrl).then(() => {
        this.$message.info('已复制当前资讯链接！');
      }).catch(err => {
        console.log(err);
        this.$message.info('分享功能即将上线，敬请期待');
      });
    }
  }
};
</script>

<style scoped>
.news-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.news-card {
  border-radius: 8px;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.news-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.news-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.news-date {
  float: right;
  font-size: 14px;
}

.news-content {
  padding: 10px 0;
}

.news-text {
  font-size: 15px;
  line-height: 1.8;
  color: #606266;
  margin-bottom: 20px;
  padding-right: 15px;
}

.news-text >>> img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

.news-meta {
  margin-top: 20px;
}

.news-avatar {
  width: 100%;
  height: 300px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.news-avatar:hover {
  transform: translateY(-5px);
}

.news-footer {
  margin-top: 20px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}


/*评论*/
.comment-container {
  background-color: #f5f7fa;
}

.comment-list {
  margin-top: 20px;
}

.comment-card {
  overflow: hidden;
  transition: transform 0.3s;
  margin-bottom: 20px;
}

.comment-card:hover {
  transform: translateY(-5px);
}

.comment-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #ffffff;
  border-bottom: 1px solid #eaeaea;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.comment-user-info {
  flex: 1;
}

.comment-username {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.comment-date {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.comment-content {
  margin-top: 10px;
}
</style>